<template>
  <div class='dish'>
    <el-page-header @back="backDish" :content="title" fixed>
    </el-page-header>
    <el-form ref="form" :model="DishBasic" :rules="DishRules" label-width="100px" label-position="left" style="margin: 56px 80px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="菜品名称:" prop="dishName">
            <el-input v-model="DishBasic.dishName" style="width: 280px;" placeholder="请输入菜品名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜品分类:" prop="categoryId">
            <el-select v-model="DishBasic.categoryId" placeholder="请选择菜品分类" style="width: 280px;">
              <el-option v-for="item in categoryList" :key="item.id" :label="item.categoryName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="售价:" prop="price">
        <el-input v-model="DishBasic.price" style="width: 280px;" placeholder="请输入售价"></el-input>
      </el-form-item>
      <el-form-item label="排序:">
        <el-input v-model="DishBasic.sort" style="width: 280px;" placeholder="请输入排序"></el-input>
      </el-form-item>
      <el-form-item label="口味配置:">
        <el-button type="warning" @click="addFlavor" v-if="dishFlavorList.length == 0"
          icon="el-icon-plus">添加口味</el-button>
        <div class="flavorlist" v-if="dishFlavorList.length != 0">
          <div class="title">
            <span>口味名（3个字内）</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>口味标签</span>
          </div>
          <div class="content">
            <div class="flavorItem" v-for="(item,index) in dishFlavorList" :key="index">
              <el-row :gutter="15">
                <el-col :span="4">
                  <el-select placeholder="请输入口味" @change="changeFlavor" v-model="item.flavorName">
                    <el-option v-for="(dishFlavor,index) in dishFlavorData" :label="dishFlavor.name" :value="dishFlavor.name"
                      :key="index"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="16">
                  <div class="tags">
                    <el-tag v-for="tag in item.flavorList" :key="tag.name" style="margin-right: 5px;margin-left: 5px;"
                      :disable-transitions="true">
                      {{ tag.name }}
                    </el-tag>
                  </div>
                </el-col>
                <el-col :span="4">
                  <el-button type="text" @click="delFlavor(index)">删除</el-button>
                </el-col>
              </el-row>
            </div>
          </div>
          <div class="addBut">
            <el-button type="warning" @click="addFlavor">添加口味</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="菜品图片:">
        <el-upload action list-type="picture-card" :http-request="uploadFile" :limit="3" :file-list="fileList"
          :on-remove="handleRemove" :on-exceed="limitFile">
          <i slot="default" class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="描述:">
        <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="DishBasic.description" style="width: 803px;">
        </el-input>
      </el-form-item>
      <div style="margin-top: 35px"></div>
      <el-form-item>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-button type="primary" @click="addOrEditDish">保存</el-button>
          </el-col>
          <el-col :span="4">
            <el-button @click="resetForm">重置</el-button>
          </el-col>
          <el-col :span="4">
            <el-button @click="backDish">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import request from '@/utils/request'

export default {
  name: '',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
  // 这里存放数据
    return {
      baseDish: '/dish-basic',
      title: '添加菜品',
      flag: true,
      id: 0,
      // 菜品对象
      DishBasic: {
        id: 0,
        dishName: '',
        categoryId: '',
        price: 0,
        image: '',
        status: 0,
        description: '',
        dishFlavors: [],
        sort: 0,
        createUser: 0,
        // createDate: new Date(),
        updateUser: 0,
        // updateDate: new Date(),
        isDeleted: false
      },
      categoryList: [],
      fileList: [],
      dishFlavorData: [
        { name: '甜味', value: ['无糖', '少糖', '半糖', '多糖', '全糖'] },
        { name: '温度', value: ['热饮', '常温', '去冰', '少冰', '多冰'] },
        { name: '忌口', value: ['不要葱', '不要蒜', '不要香菜', '不要辣'] },
        { name: '辣度', value: ['不辣', '微辣', '中辣', '重辣'] }
      ],
      dishFlavorList: [
      ],
      DishRules: {
        dishName: [
          { required: true, message: '请输入菜品名称', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择菜品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入菜品价格', trigger: 'blur' }
        ]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    async searchCategoryListByType () {
      await request({
        url: '/category-basic/category-list/1/1000',
        method: 'get',
        params: {
          type: 1
        }
      }).then(result => {
        this.categoryList = result.data.data.data
      })
    },
    // 回显菜品信息
    async backDishById () {
      this.fileList = []
      if (this.flag) {
        // 添加菜品，不需要回显数据
        // 显示当前标题为添加菜品
        this.title = '添加菜品'
      } else {
        // 编辑菜品，需要回显数据
        // 显示当前标题为编辑菜品
        this.title = '编辑菜品'
        // 回显数据
        await request({
          url: this.baseDish + `/dish-basic/${this.id}`,
          method: 'get'
        }).then(result => {
          if (result.data.data != null) {
            const { id, dishName, categoryId, price, sort, status, dishFlavors, image, description } = result.data.data
            this.DishBasic = { id, dishName, categoryId, price, sort, status, dishFlavors, image, description }
            this.dishFlavorList = []
            if (this.DishBasic.dishFlavors !== '') {
              const dishFlavors = []
              this.DishBasic.dishFlavors.forEach(item => {
                const dishFlavor = {
                  flavorName: '',
                  flavorList: []
                }
                dishFlavor.flavorName = item.flavorName
                dishFlavor.flavorList = JSON.parse(item.flavorList)
                dishFlavors.push(dishFlavor)
              })
              console.log(dishFlavors)
              console.log(this.dishFlavorList)
              this.dishFlavorList = dishFlavors
              console.log(this.dishFlavorList)
            }
            if (this.DishBasic.image !== '') {
              const urlList = this.DishBasic.image.split(',')
              urlList.forEach(item => {
                const image = {
                  url: ''
                }
                image.url = item
                this.fileList.push(image)
              })
            }
          } else {
            this.$message({
              message: '回显失败',
              type: 'error'
            })
          }
        }).catch(err => {
          console.log(err)
          this.$message({
            message: '回显失败',
            type: 'error'
          })
        })
      }
    },
    // 添加或修改菜品
    async addOrEditDish () {
      const urlList = []
      this.fileList.forEach(item => {
        urlList.push(item.url)
      })
      this.DishBasic.image = urlList.join(',')
      this.DishBasic.image.substring(1)
      const dishFlavors = []
      this.dishFlavorList.forEach(item => {
        const flavor = {
          flavorName: '',
          flavorList: ''
        }
        flavor.flavorName = item.flavorName
        flavor.flavorList = JSON.stringify(item.flavorList)
        dishFlavors.push(flavor)
      })
      this.DishBasic.dishFlavors = dishFlavors
      if (this.flag) {
        // 添加菜品
        await request({
          url: this.baseDish + '/dish-basic',
          method: 'post',
          data: this.DishBasic
        }).then(result => {
          if (result.data.data) {
            this.backDish('添加成功')
            this.urlList = []
            this.fileList = []
          } else {
            this.$message({
              message: '添加失败',
              type: 'error'
            })
          }
        }).catch(err => {
          console.log(err)
          this.$message({
            message: '添加失败',
            type: 'error'
          })
        })
      } else {
        // 修改菜品
        await request({
          url: this.baseDish + '/dish-basic',
          method: 'put',
          data: this.DishBasic
        }).then(res => {
          if (res.data.data) {
            this.backDish('修改成功')
            this.urlList = []
            this.fileList = []
          } else {
            this.$message({
              message: '修改失败',
              type: 'error'
            })
          }
        }).catch(err => {
          console.log(err)
          this.$message({
            message: '修改失败',
            type: 'error'
          })
        })
      }
    },
    // 返回菜品界面返回信息
    backDish (msg) {
      this.$router.push({
        path: '/dish',
        query: {
          msg
        }
      })
    },
    // 重置表单数据
    resetForm () {
      this.DishBasic = {
        id: 0,
        dishName: '',
        categoryId: 0,
        price: 0,
        image: '',
        status: 0,
        description: '',
        dishFlavors: [],
        sort: 0,
        createUser: 0,
        createDate: new Date(),
        updateUser: 0,
        updateDate: new Date(),
        isDeleted: false
      }
    },
    /**
     * 文件上传
     */
    async uploadFile (file) {
      const fileData = new FormData()
      fileData.append('file', file.file)
      await request.post(
        '/file/upload-file',
        fileData,
        {
          'Content-Type': 'multipart/form-data;charset=utf-8'
        }
      ).then(res => {
        if (res.data.data != null) {
          const imageUrl = {
            url: ''
          }
          imageUrl.url = res.data.data
          this.fileList.push(imageUrl)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleRemove (file) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    addFlavor () {
      this.dishFlavorList.push({ flavorName: '', flavorList: [] })
    },
    changeFlavor (flavorName) {
      const dishFlavor = {
        flavorName: '',
        flavorList: []
      }
      dishFlavor.flavorName = flavorName
      this.dishFlavorData.forEach(flavor => {
        if (flavor.name === flavorName) {
          const tags = []
          flavor.value.forEach(item => {
            const tag = {
              name: ''
            }
            tag.name = item
            tags.push(tag)
          })
          dishFlavor.flavorList = tags
        }
      })
      this.dishFlavorList = this.dishFlavorList.slice(0, -1)
      this.dishFlavorList.push(dishFlavor)
    },
    delFlavor (index) {
      this.dishFlavorList.splice(index, 1)
      console.log(this.dishFlavorList)
    },
    limitFile () {
      this.$message({
        message: '当前只允许上传三张图片',
        type: 'error'
      })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.flag = this.$route.params.flag
    this.id = this.$route.params.id
    this.searchCategoryListByType()
    this.backDishById()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="less" scoped>
.dish {
    background-color: #fff;
    /* height: 810px; */
    padding: 20px 20px;
    border-radius: 30px;
  }
.flavorlist {
  background-color: rgb(234, 230, 230);
  padding: 20px;

  .content {

    .flavorItem {
      margin-bottom: 10px;
    }

    .tags {
      background-color: #fff;
      width: 560px;
      height: 40px;
      border-radius: 5px;
    }
  }
  .addBut {
    margin-top: 20px;
  }
}

</style>
